package flc.ast.fragment;

import static android.app.Activity.RESULT_OK;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.activity.ConvPdfActivity;
import flc.ast.activity.ConvRecordActivity;
import flc.ast.activity.InputTextActivity;
import flc.ast.activity.SelPictureActivity;
import flc.ast.adapter.ConvRecordAdapter;
import flc.ast.bean.MyConvRecordBean;
import flc.ast.databinding.FragmentToolBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.UriUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ToolFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ToolFragment extends BaseNoModelFragment<FragmentToolBinding> {

    ConvRecordAdapter recordAdapter;
    private Dialog myMoreDialog;
    private Dialog myRenameDialog;
    private EditText editText;
    private List<MyConvRecordBean> listShow = new ArrayList<>();
    private String selPath = "";

    @Override
    protected int onCreate() {
        return R.layout.fragment_tool;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.ivConvPicture.setOnClickListener(this);
        mDataBinding.ivConvText.setOnClickListener(this);
        mDataBinding.ivConvPdf.setOnClickListener(this);
        mDataBinding.tvMore.setOnClickListener(this);

        mDataBinding.rvRecordList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        recordAdapter = new ConvRecordAdapter();
        mDataBinding.rvRecordList.setAdapter(recordAdapter);
        recordAdapter.addChildClickViewIds(R.id.ivConvRecordItemMore);
        recordAdapter.setOnItemClickListener(this);
        recordAdapter.setOnItemChildClickListener(this);
        //更多弹框
        moreDialog();
        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivConvPicture://图片转pdf
                startActivity(SelPictureActivity.class);
                break;
            case R.id.ivConvText://文本转pdf
                startActivity(InputTextActivity.class);
                break;
            case R.id.ivConvPdf://pdf转图片
                getPermission();
                break;
            case R.id.tvMore://历史记录
                startActivity(ConvRecordActivity.class);
                break;
            //更多弹框
            case R.id.tvDialogMoreRename://重命名
                myMoreDialog.dismiss();
                myRenameDialog.show();
                break;
            case R.id.tvDialogMoreSave://保存到手机
                myMoreDialog.dismiss();
                save();
                break;
            case R.id.tvDialogMoreDelete://删除
                myMoreDialog.dismiss();
                delete();
                break;
            case R.id.tvDialogMoreCancel://取消
                myMoreDialog.dismiss();
                break;
            //重命名
            case R.id.ivDialogRenameConfirm:
                String name = editText.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getText(R.string.please_input_file_name));
                    return;
                }
                FileUtils.rename(selPath, name + "." + FileUtils.getFileExtension(selPath));
                myRenameDialog.dismiss();
                editText.setText("");
                getData();
                break;
            case R.id.ivDialogRenameCancel:
                editText.setText("");
                myRenameDialog.dismiss();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivConvRecordItemMore:
                selPath = recordAdapter.getItem(position).getPath();
                myMoreDialog.show();
                break;
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    //获取记录数据
    private void getData() {
        listShow.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myConvRecord;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 3) {
            files = files.subList(0, 3);
        }
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(new MyConvRecordBean(file.getPath(), file.getName(),
                        TimeUtils.millis2String(FileUtils.getFileLastModified(file), "yyyy-MM-dd HH:mm"),
                        FileUtils.getSize(file), false));
            }
        }
        if (listShow.size() > 0) {
            recordAdapter.setList(listShow);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
            mDataBinding.ivRecordNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvRecordList.setVisibility(View.GONE);
            mDataBinding.ivRecordNoData.setVisibility(View.VISIBLE);
        }
    }

    //保存
    private void save() {
        showDialog(getString(R.string.save_ing));
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                if (ImageUtils.isImage(selPath)) {
                    FileP2pUtil.copyPrivateImgToPublic(mContext, selPath);
                } else {
                    String suffix = FileUtils.getFileExtension(selPath);
                    String desPath = PathUtils.getFilesPathExternalFirst() + FileUtils.getFileNameNoExtension(selPath) + "." + suffix;
                    FileUtils.copy(selPath, desPath);
                }
                emitter.onNext("");
            }

            @Override
            public void accept(String path) {
                dismissDialog();
                ToastUtils.showShort(R.string.download_suc);
            }
        });
    }

    //删除
    private void delete() {
        RxUtil.create(new RxUtil.Callback<String>() {

            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                FileUtils.delete(selPath);
                emitter.onNext("");
            }

            @Override
            public void accept(String path) {
                ToastUtils.showShort(getString(R.string.delete_suc));
                getData();
            }
        });
    }


    //更多弹框
    private void moreDialog() {
        myMoreDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_more, null);
        myMoreDialog.setContentView(inflate);
        myMoreDialog.setCancelable(false);
        Window dialogWindow = myMoreDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 80;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogRename = inflate.findViewById(R.id.tvDialogMoreRename);
        TextView dialogSave = inflate.findViewById(R.id.tvDialogMoreSave);
        TextView dialogDelete = inflate.findViewById(R.id.tvDialogMoreDelete);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogMoreCancel);
        dialogRename.setOnClickListener(this);
        dialogSave.setOnClickListener(this);
        dialogDelete.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogRenameCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogRenameConfirm);
        editText = inflate.findViewById(R.id.etDialogFormatRename);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private void getPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission().reqPermissionDesc(getString(R.string.get_manage_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("application/pdf");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                try {
                    startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 120);
                } catch (android.content.ActivityNotFoundException ex) {
                }
            }
        }).request();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 120) {
                Uri uri = data.getData();
                if (uri == null) {
                    return;
                }
                ConvPdfActivity.uri = uri;
                startActivity(ConvPdfActivity.class);
            }
        }
    }

}